package ru.ksu.ktk.diploma.sdi.mapping.impl;

import java.util.ArrayList;
import java.util.List;

import ru.ksu.ktk.diploma.sdi.mapping.*;
import ru.ksu.ktk.diploma.sdi.mapping.loaders.ResourceLoader;
import ru.ksu.ktk.diploma.sdi.mapping.resolver.MappingElementsResolver;
import ru.ksu.ktk.diploma.sdi.mapping.resolver.MappingResolver;

import com.hp.hpl.jena.ontology.OntModel;

public class MappingGeneratorImpl implements MappingGenerator {

    /**
     * mapping loader
     */
    private ResourceLoader mappingLoader;
    /**
     * resolver to find mapping elements
     */
    private MappingElementsResolver mappingElementsResolver;

    private MappingResolver mappingResolver;

    /**
     * @see MappingGenerator#getCorrespondences(String)
     */
    public List<Correspondence> getCorrespondences(OntModel sourceDataModel) {

        List<MappingElement> mappingElements = mappingElementsResolver.findMatch(sourceDataModel);
        return getCorrespondences(mappingElements);
    }

    /**
     * @see MappingGenerator#generateMapping(List)
     */
    public List<Triple> generateMapping(List<Correspondence> correspondences) {
        return mappingResolver.findMapping(correspondences);
    }

    public ResourceLoader getMappingLoader() {
        return mappingLoader;
    }

    public void setMappingLoader(ResourceLoader mappingLoader) {
        this.mappingLoader = mappingLoader;
    }

    public MappingElementsResolver getMappingElementsResolver() {
        return mappingElementsResolver;
    }

    public void setMappingElementsResolver(MappingElementsResolver mappingElementsResolver) {
        this.mappingElementsResolver = mappingElementsResolver;
    }

    public MappingResolver getMappingResolver() {
        return mappingResolver;
    }

    public void setMappingResolver(MappingResolver mappingResolver) {
        this.mappingResolver = mappingResolver;
    }

    private List<Correspondence> getCorrespondences(List<MappingElement> mapping) {
        List<Correspondence> correspondences = new ArrayList<Correspondence>();
        for (MappingElement mappingElement : mapping){
            Correspondence correspondence = new Correspondence(mappingElement.getSrcClassURI());
            int corresponceIndex = correspondences.indexOf(correspondence);
            if (corresponceIndex != -1){
                Correspondence foundCorrespondence = correspondences.get(corresponceIndex);
                foundCorrespondence.addMappingElement(mappingElement);
            }
            else{
                correspondence.addMappingElement(mappingElement);
                correspondences.add(correspondence);
            }
        }
        return correspondences;
    }
}
